// 日期格式化
export const formatDate = (date: string | Date, format = 'YYYY-MM-DD'): string => {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hour = String(d.getHours()).padStart(2, '0');
  const minute = String(d.getMinutes()).padStart(2, '0');
  
  switch (format) {
    case 'YYYY-MM-DD':
      return `${year}-${month}-${day}`;
    case 'MM-DD':
      return `${month}-${day}`;
    case 'YYYY-MM-DD HH:mm':
      return `${year}-${month}-${day} ${hour}:${minute}`;
    case 'HH:mm':
      return `${hour}:${minute}`;
    default:
      return `${year}-${month}-${day}`;
  }
};

// 相对时间格式化
export const formatRelativeTime = (date: string | Date): string => {
  const now = new Date();
  const target = new Date(date);
  const diff = now.getTime() - target.getTime();
  
  const minute = 60 * 1000;
  const hour = minute * 60;
  const day = hour * 24;
  const week = day * 7;
  const month = day * 30;
  
  if (diff < minute) {
    return '刚刚';
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`;
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`;
  } else if (diff < week) {
    return `${Math.floor(diff / day)}天前`;
  } else if (diff < month) {
    return `${Math.floor(diff / week)}周前`;
  } else {
    return formatDate(date, 'YYYY-MM-DD');
  }
};

// 文本摘要
export const getTextSummary = (text: string, maxLength = 100): string => {
  if (text.length <= maxLength) {
    return text;
  }
  return text.substring(0, maxLength) + '...';
};

// 字数统计
export const getWordCount = (text: string): number => {
  // 中文字符和英文单词分别计数
  const chineseCount = (text.match(/[\u4e00-\u9fa5]/g) || []).length;
  const englishCount = (text.match(/[a-zA-Z]+/g) || []).length;
  return chineseCount + englishCount;
};

// 标签处理
export const parseTags = (tags: string | string[]): string[] => {
  if (Array.isArray(tags)) {
    return tags;
  }
  if (typeof tags === 'string') {
    return tags.split(',').map(tag => tag.trim()).filter(tag => tag.length > 0);
  }
  return [];
};

// 情绪分数转换为文字
export const getMoodText = (score?: number): string => {
  if (score === undefined || score === null) {
    return '未知';
  }
  
  if (score >= 8) return '非常开心';
  if (score >= 6) return '愉快';
  if (score >= 4) return '平静';
  if (score >= 2) return '低落';
  return '沮丧';
};

// 情绪分数转换为颜色
export const getMoodColor = (score?: number): string => {
  if (score === undefined || score === null) {
    return '#999';
  }
  
  if (score >= 8) return '#52c41a'; // 绿色
  if (score >= 6) return '#1890ff'; // 蓝色
  if (score >= 4) return '#faad14'; // 黄色
  if (score >= 2) return '#fa8c16'; // 橙色
  return '#f5222d'; // 红色
};

// 防抖函数
export const debounce = <T extends (...args: any[]) => any>(
  func: T,
  wait: number
): ((...args: Parameters<T>) => void) => {
  let timeout: any;
  return (...args: Parameters<T>) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => func(...args), wait);
  };
};

// 节流函数
export const throttle = <T extends (...args: any[]) => any>(
  func: T,
  limit: number
): ((...args: Parameters<T>) => void) => {
  let inThrottle: boolean;
  return (...args: Parameters<T>) => {
    if (!inThrottle) {
      func(...args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
};

// 生成唯一ID
export const generateId = (): string => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
};

// 存储相关
export const storage = {
  set: (key: string, value: any): void => {
    try {
      const serializedValue = JSON.stringify(value);
      if (typeof localStorage !== 'undefined') {
        localStorage.setItem(key, serializedValue);
      }
    } catch (error) {
      console.error('存储数据失败:', error);
    }
  },
  
  get: <T = any>(key: string, defaultValue?: T): T | null => {
    try {
      if (typeof localStorage === 'undefined') {
        return defaultValue || null;
      }
      const item = localStorage.getItem(key);
      if (item === null) {
        return defaultValue || null;
      }
      return JSON.parse(item);
    } catch (error) {
      console.error('读取数据失败:', error);
      return defaultValue || null;
    }
  },
  
  remove: (key: string): void => {
    try {
      if (typeof localStorage !== 'undefined') {
        localStorage.removeItem(key);
      }
    } catch (error) {
      console.error('删除数据失败:', error);
    }
  },
}; 